package com.iye.puretennis.fragment;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.CustomViewFlipper;
import com.iye.puretennis.custom.HuaWenHuPoTextView;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.utils.TimeUtils;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: Chuanbao on 2014/11/25.
 */
public class AvailableFragment extends TabFragment {

    public static final String TAG = "AvailableFragment";

    CustomViewFlipper viewFlipper;

    ViewElement[] viewElements = new ViewElement[2];

    int totalNum = 14;

    View flipperView1;

    View flipperView2;


    @Override
    public void onCustomCreateView(LayoutInflater inflater) {

        viewFlipper = (CustomViewFlipper) mainView.findViewById(R.id.availabilityViewFlipper);

        flipperView1 = inflater.inflate(R.layout.available_flipper_view, null);

        flipperView2 = inflater.inflate(R.layout.available_flipper_view, null);

        viewElements[0] = new ViewElement(flipperView1, 0);

        viewElements[1] = new ViewElement(flipperView2, 1);

        viewFlipper.setMyViewFlipper(totalNum, false, 0, new View[]{flipperView1,
                flipperView2}, loadViewData, loadViewData);


    }


    CustomViewFlipper.MyViewFlipperLoadData loadViewData = new CustomViewFlipper.MyViewFlipperLoadData() {
        public void loadData(final int index) {
            //the start date of current page
            String startDate = TimeUtils.getFirstDayOfWeek(viewFlipper.getCurrentDataIndex());
            //the end date of current page
            String endDate = TimeUtils.plusDays(startDate, 6);
            availabilityRender(startDate, endDate, viewElements[index].lv);
        }

        @Override
        public boolean canLoadData() {
            return true;
        }
    };

    private void availabilityRender(final String startDate, final String endDate, final ListView listView) {
        Log.d(TAG, "call remote server.");
        new Thread(new Runnable() {
            @Override
            public void run() {
                long start = System.currentTimeMillis();
                String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.MY_AVAILABLES) + "/" + startDate + "/" + endDate, token.getToken());
                if (!Constant.RESPONSE_BADLY.equals(result)) {
                    try {
                        final List<MyAvailable> availables = new ArrayList<MyAvailable>();
                        JSONArray array = new JSONArray(result);
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject jsonObject = array.getJSONObject(i);
                            String date = jsonObject.getString("date");
                            JSONObject availabilityObj = jsonObject.getJSONObject("availability");
                            String morning = availabilityObj.getString("morning");
                            String afternoon = availabilityObj.getString("afternoon");
                            String evening = availabilityObj.getString("evening");
                            MyAvailable myAvailable = new MyAvailable(date, morning, afternoon, evening);
                            availables.add(myAvailable);
                        }
                        Log.d(TAG, "server request:" + (System.currentTimeMillis() - start));
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listView.setAdapter(new MyAvailableAdapter(R.layout.myavailable_item, availables));
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }


    @Override
    public void updateUI() {
    }

    @Override
    public int getViewId() {
        return R.layout.myavailable;
    }

    @Override
    public int getSourceId() {
        return R.id.my_available;
    }

    @Override
    public boolean isParent() {
        return true;
    }

    private class MyAvailable {
        private String date;

        private String morning;

        private String afternoon;

        private String evening;

        public MyAvailable(String date, String morning, String afternoon, String evening) {
            this.date = date;
            this.morning = morning;
            this.afternoon = afternoon;
            this.evening = evening;
        }

        public boolean isScheduledPeriod(String period) {
            switch (Period.valueOf(period)) {
                case MORNING:
                    return Availability.SCHEDULED.name().equals(morning);
                case AFTERNOON:
                    return Availability.SCHEDULED.name().equals(afternoon);
                case EVENING:
                    return Availability.SCHEDULED.name().equals(evening);
                default:
                    return true;
            }
        }
    }

    private enum Availability {
        YES,
        NO,
        SCHEDULED
    }

    private enum Period {
        MORNING,
        AFTERNOON,
        EVENING
    }

    private class MyAvailableAdapter extends BaseAdapter {
        LayoutInflater inflater;
        int resource;
        List<MyAvailable> availables;
        ViewCache viewCache;

        public MyAvailableAdapter(int resource, List<MyAvailable> availables) {
            this.resource = resource;
            this.availables = availables;
            inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return availables.size();
        }

        @Override
        public Object getItem(int position) {
            return availables.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HuaWenHuPoTextView dateView;
            View morningView, afternoonView, eveningView;
            if (convertView == null) {
                convertView = inflater.inflate(resource, null);
                dateView = (HuaWenHuPoTextView) convertView.findViewById(R.id.date);
                morningView = convertView.findViewById(R.id.morning);
                afternoonView = convertView.findViewById(R.id.afternoon);
                eveningView = convertView.findViewById(R.id.evening);

                viewCache = new ViewCache();
                viewCache.dateView = dateView;
                viewCache.morningView = morningView;
                viewCache.afternoonView = afternoonView;
                viewCache.eveningView = eveningView;

                convertView.setTag(viewCache);
            } else {
                viewCache = (ViewCache) convertView.getTag();
                dateView = viewCache.dateView;
                morningView = viewCache.morningView;
                afternoonView = viewCache.afternoonView;
                eveningView = viewCache.eveningView;

            }


            MyAvailable myAvailable = availables.get(position);
            String day = myAvailable.date.substring(0, 10);
            dateView.setText(myAvailable.date.substring(5, 10) + "\n（" + TimeUtils.getDayOfWeek(position) + "）");
            if (TimeUtils.isToday(day)) {

                dateView.setTextColor(getResources().getColor(R.color.yellow));
            }
            if (Availability.YES.name().equals(myAvailable.morning)) {
                morningView.findViewById(R.id.morning_round).setVisibility(View.VISIBLE);
            }
            morningView.setOnClickListener(new ToggleMyAvailableListener(position, myAvailable.date, Period.MORNING.name()));
            if (Availability.YES.name().equals(myAvailable.afternoon)) {
                afternoonView.findViewById(R.id.afternoon_round).setVisibility(View.VISIBLE);
            }
            afternoonView.setOnClickListener(new ToggleMyAvailableListener(position, myAvailable.date, Period.AFTERNOON.name()));
            if (Availability.YES.name().equals(myAvailable.evening)) {
                eveningView.findViewById(R.id.evening_round).setVisibility(View.VISIBLE);
            }
            eveningView.setOnClickListener(new ToggleMyAvailableListener(position, myAvailable.date, Period.EVENING.name()));
            return convertView;
        }

        private class ViewCache {
            HuaWenHuPoTextView dateView;
            View morningView;
            View afternoonView;
            View eveningView;

        }

        //field area click listener
        private class ToggleMyAvailableListener implements View.OnClickListener {
            int position;
            String date;
            String period;

            private ToggleMyAvailableListener(int position, String date, String period) {
                this.position = position;
                this.date = date;
                this.period = period;
            }

            @Override
            public void onClick(final View v) {
                final MyAvailable myAvailable = availables.get(position);
                if (myAvailable.isScheduledPeriod(period)) {
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("date", date);
                            jsonObject.put("period", period);
                            StringEntity paramEntity = new StringEntity(jsonObject.toString(), Constant.CHARSET_UTF8);
                            String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.MY_AVAILABLE_TOGGLE), token.getToken(), paramEntity);
                            if (!Constant.RESPONSE_BADLY.equals(result)) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        switch (Period.valueOf(period)) {
                                            case MORNING:
                                                View morningRound = v.findViewById(R.id.morning_round);
                                                if (myAvailable.morning.equals(Availability.NO.name())) {
                                                    morningRound.setVisibility(View.VISIBLE);
                                                    myAvailable.morning = Availability.YES.name();
                                                } else if (myAvailable.morning.equals(Availability.YES.name())) {
                                                    morningRound.setVisibility(View.GONE);
                                                    myAvailable.morning = Availability.NO.name();
                                                }
                                                break;
                                            case AFTERNOON:
                                                View afternoonRound = v.findViewById(R.id.afternoon_round);

                                                if (myAvailable.afternoon.equals(Availability.NO.name())) {
                                                    afternoonRound.setVisibility(View.VISIBLE);
                                                    myAvailable.afternoon = Availability.YES.name();
                                                } else if (myAvailable.afternoon.equals(Availability.YES.name())) {
                                                    afternoonRound.setVisibility(View.GONE);
                                                    myAvailable.afternoon = Availability.NO.name();
                                                }
                                                break;
                                            case EVENING:
                                                View eveningRound = v.findViewById(R.id.evening_round);

                                                if (myAvailable.evening.equals(Availability.NO.name())) {
                                                    eveningRound.setVisibility(View.VISIBLE);
                                                    myAvailable.evening = Availability.YES.name();
                                                } else if (myAvailable.evening.equals(Availability.YES.name())) {
                                                    eveningRound.setVisibility(View.GONE);
                                                    myAvailable.evening = Availability.NO.name();
                                                }
                                                break;
                                        }
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }
        }
    }

    public class ViewElement {
        ListView lv;

        public ViewElement(View view, int index) {
            lv = (ListView) view.findViewById(R.id.available_gridView);

            if (index == 0) {
                String startDate = TimeUtils.getFirstDayOfWeek(0);
                String endDate = TimeUtils.plusDays(startDate, 6);
                availabilityRender(startDate, endDate, lv);
            }
            // ScrollView滑动时触发切换事件
            viewFlipper.setChildTouchListener(this.lv);
        }
    }
}
